package com.woniu.task;

import com.woniu.config.ContainerCache;
import com.woniu.utils.DockerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author hq
 * @Date 2025/6/18$ 14:53$
 * @Description TODO
 * @Params $
 * @Return $
 **/
@Component
public class ContainerCleanupTask {

    @Autowired
    private DockerUtils dockerUtils;

    @Autowired
    private ContainerCache containerCache;

    // 默认1小时 = 3600秒
    private static final long TIMEOUT_MILLIS = 6000 * 1000;

    @Scheduled(fixedRate = 60_000) // 每分钟执行一次
    public void checkAndDestroyExpiredContainers() {
        Map<String, Long> containers = containerCache.getAllContainers();

        for (Map.Entry<String, Long> entry : containers.entrySet()) {
            String containerId = entry.getKey();
            long startTime = entry.getValue();

            if (System.currentTimeMillis() - startTime > TIMEOUT_MILLIS) {
                // 停止容器
                dockerUtils.stopAndRemoveContainer(containerId);

                // 从缓存中移除
                containerCache.removeContainer(containerId);

                System.out.println("✅ 容器已过期并清理: " + containerId);
            }
        }
    }
}
